<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BookResource\Pages;
use App\Filament\Resources\BookResource\RelationManagers;
use App\Models\Book;
use App\Models\Category;
use CodeWithDennis\FilamentSelectTree\SelectTree;
use Filament\Forms;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Support\Colors\Color;
use Filament\Support\Enums\Alignment;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Filament\Tables\Actions\Action;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Livewire\Component;

class BookResource extends Resource
{
    protected static ?string $model = Book::class;

    protected static ?string $navigationIcon = 'heroicon-o-book-open';
    protected static ?string $navigationLabel = '图书列表';

    protected static ?string $navigationGroup = '图书管理';

    protected static ?string $modelLabel = '图书';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                    Forms\Components\Section::make()
                        ->schema([
                            Grid::make(2)->schema([
                                Forms\Components\TextInput::make('title')
                                    ->label('标题')
                                    ->required()
                                    ->maxLength(255),
                                Textarea::make('description')
                                    ->label('介绍')
                                    ->autosize(),
                                Forms\Components\FileUpload::make('img')
                                    ->label('封面')
                                    ->image()
                                    ->imageEditor()
                                    ->required(),
                                SelectTree::make('category_id')
                                    ->required()
                                    ->label('所属类目')
                                    ->relationship('category', 'name','parent_id')
                                    ->enableBranchNode()
                                    ->emptyLabel('没有相关数据呢')
                                    ->placeholder('请选择所属类目'),
                                Forms\Components\TextInput::make('weight')
                                    ->numeric()
                                    ->label('权重')
                                    ->default(100)
                                    ->required(),
                                Forms\Components\Toggle::make('status')
                                    ->label('状态')
                                    ->inline(false)
                                    ->default(true)
                                    ->required(),
                                Forms\Components\TextInput::make('author')
                                    ->label('作者')
                                    ->required()
                                    ->maxLength(255),
                                Forms\Components\TagsInput::make('tag')
                                    ->label('标签'),
                                Forms\Components\TextInput::make('quantity')
                                    ->numeric()
                                    ->label('库存')
                                    ->default(0)
                                    ->required(),
                                Forms\Components\TextInput::make('price')
                                    ->numeric()
                                    ->label('价格')
                                    ->default(0)
                                    ->required(),
                            ])

                        ])


            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->paginated([8,12, 24, 48, 96, 'all'])
            ->defaultPaginationPageOption(8)
            ->defaultSort('created_at', 'desc')
            ->contentGrid([
                'md' => 3,
                'xl' => 4,
            ])
            ->columns([
                Tables\Columns\Layout\Stack::make([

                    Tables\Columns\ImageColumn::make('img')
                        ->checkFileExistence(false)
                        ->width('100%')
                        ->height('18rem'),
                    Tables\Columns\TextColumn::make('title')
                        ->weight(FontWeight::Bold)
                        ->searchable(),
                    Tables\Columns\TextColumn::make('author')
                        ->color(Color::Gray),
                    Tables\Columns\TextColumn::make('status')
                        ->label('状态'),
                    Tables\Columns\TextColumn::make('quantity')
                        ->label('库存')
                        ->formatStateUsing(fn (int $state) => "库存： {$state}")
                        ->color('gray')
                ])->space(1)

            ])
            ->filters([
                //
                Filter::make('tree')
                    ->label('类目')
                    ->form([
                        SelectTree::make('category_id')
                            ->label('类目')
                            ->relationship('category', 'name', 'parent_id')
                            ->independent(false)
                            ->enableBranchNode(),
                    ])
                    ->query(function (Builder $query, array $data) {

                        return $query->when($data['category_id'], function ($query, $categories) {

                            return $query->whereHas('category', fn($query) => $query->whereIn('id', is_array($categories) ? $categories : [$categories]));
                        });
                    })
                    ->indicateUsing(function (array $data): ?string {

                        if (! $data['category_id']) {
                            return null;
                        }

                        return  '类目: ' . implode(', ', Category::whereIn('id', is_array($data['category_id']) ? $data['category_id'] : [$data['category_id']])->get()->pluck('name')->toArray());
                    })
            ])
            ->actions([
                Action::make('section')
                ->label('章节')
                ->icon('heroicon-o-arrow-down-tray')
                ->action(fn(Component $livewire,Book $record)=> $livewire::importSection($record)),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make()->label('报废')
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
            RelationManagers\ChaptersRelationManager::class
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBooks::route('/'),
            'create' => Pages\CreateBook::route('/create'),
            'edit' => Pages\EditBook::route('/{record}/edit'),
        ];
    }


}
